package com.roy.netty.epoll;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/6
 * @description:
 **/

public class NettyServer {
    public static void main(String[] args) {
        int port = 8080;
        // 创建两个线程组，这两个都是无限循环的任务组。
        // bossGroup只负责处理连接请求，所以他的线程数可以配置得低一点。
        // workGroup负责调度实际业务处理，并向客户端发送响应，所以通常线程数配置得要多一点。默认是CPU核心数*2
        EventLoopGroup bossGroup;
        EventLoopGroup workerGroup;
        int cors = Runtime.getRuntime().availableProcessors()*2 ;

        if(useEpoll()){
            bossGroup = new EpollEventLoopGroup(1, new ThreadFactory() {
                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, String.format("NettyEPOLLBoss_%d", this.threadIndex.incrementAndGet()));
                }
            });

            workerGroup = new EpollEventLoopGroup(0, new ThreadFactory() {
                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, String.format("NettyServerEPOLLSelector_%d_%d", cors, this.threadIndex.incrementAndGet()));
                }
            });
        }else{
            bossGroup = new NioEventLoopGroup(1, new ThreadFactory() {
                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, String.format("NettyNIOBoss_%d", this.threadIndex.incrementAndGet()));
                }
            });
            workerGroup = new NioEventLoopGroup(0, new ThreadFactory() {
                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, String.format("NettyServerNIOSelector_%d_%d", cors, this.threadIndex.incrementAndGet()));
                }
            });
        }

        //服务端核心启动器
        ServerBootstrap bootstrap = new ServerBootstrap();
        try{
            //配置两个线程组，并定制相应的属性。
            //option对应BossGroup的属性，childOption对应Worker的属性。
            //同样handler对应BossGroup的业务处理器，而childHandler对应Worker的业务处理器。
            bootstrap.group(bossGroup,workerGroup) //设置线程组
                    .channel(NioServerSocketChannel.class) // 通道实现类，跟选择的网络协议有关
                    .option(ChannelOption.SO_BACKLOG,128) //设置线程队列的连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true) //设置保持活动连接状态
//                    .handler()
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //通过pipeline组建一系列处理器。每个处理器负责处理一部分业务
                            final ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            //绑定端口，启动服务。生成一个异步通知对象Future.
            final ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("server is ready....");
            //监听服务的关键事件
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()){
                        System.out.println("服务监听端口"+port+"成功");
                    }else{
                        System.out.println("服务监听端口"+port+"失败。。。。。");
                    }
                }
            });
            //对关闭通道进行监听。
            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static Boolean useEpoll(){
        Boolean isLinuxPlatform = false, isEpollAvailable;
        String OS_NAME = System.getProperty("os.name");
        if (OS_NAME != null && OS_NAME.toLowerCase().contains("linux")) {
            isLinuxPlatform = true;
        }
        isEpollAvailable = Epoll.isAvailable();

        return isLinuxPlatform & isEpollAvailable;
    }
}
